package com.codeoss.framework.view.parser;

import org.springframework.stereotype.Service;

import com.codeoss.framework.expression.Expression;
import com.codeoss.framework.expression.ExpressionUtil;
import com.codeoss.framework.util.StringUtils;
import com.codeoss.framework.view.component.Component;
import com.codeoss.framework.view.component.Container;
import com.codeoss.framework.view.component.mobile.MListView;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

@Service("mlistviewParser")
public class MListViewParser extends AbstractComponentParser {
	protected void setAttributes(IParseContext parseContext, ObjectNode objectNode,Component component) {
		super.setAttributes(parseContext, objectNode, component);
		MListView mListView=(MListView)component;
		
		JsonNode jsonNode=objectNode.get("editable");
		if(jsonNode!=null) {
			mListView.setEditable(jsonNode.asBoolean());
		}
		ObjectNode propertyMapNode=(ObjectNode)objectNode.get("propertyMap");
		if(propertyMapNode!=null) {
			jsonNode=propertyMapNode.get("dataSource");
			if(jsonNode!=null) {
				String dataSource=propertyMapNode.get("dataSource").asText();
				mListView.setDataSource(dataSource);
			}
			jsonNode=propertyMapNode.get("formPageCode");
			if(jsonNode!=null) {
				mListView.setFormPageCode(jsonNode.asText());
			}
			
			jsonNode=propertyMapNode.get("pageable");
			if(jsonNode!=null) {
				mListView.setPageable(jsonNode.asBoolean());
			}
			
			jsonNode=propertyMapNode.get("onPagination");
			if(jsonNode!=null) {
				String onPaginationExpression=jsonNode.asText();
				if(!StringUtils.isEmpty(onPaginationExpression)) {
					String expressionType=Expression.EXPRESSION_TYPE_JAVASCRIPT;
					if(onPaginationExpression.startsWith("@")) {
						expressionType=Expression.EXPRESSION_TYPE_SPRING;
					}
					Expression expression=ExpressionUtil.convertToExpression(onPaginationExpression, expressionType);
					mListView.setOnPagination(expression);
				}
			}
		}
	}
	
	protected void parseChildren(IParseContext parseContext, ObjectNode objectNode,Container container) {
		MListView mListView=(MListView)container;
		parseContext.setAttribute("dataSource", mListView.getDataSource());
		super.parseChildren(parseContext, objectNode, container);
		parseContext.removeAttribute("dataSource");
	}
	
	@Override
	protected Component createComponent(IParseContext parseContext, ObjectNode objectNode) {
		// TODO Auto-generated method stub
		return new MListView();
	}

}
